;
$(function() {

	var myTree = tree();
	var callback = function(res) {
			console.log(JSON.stringify(res));
		}
		// 初始化树
	myTree.initTree("../jsons/menu.json", "#treeContainer", "#saveTree", callback, true);
})

function tree() {

	// 初始化树
	function initTree(url, domID, btnID, callback, simpleData) {
		$.get(url, function(result) {

			$(domID).append(loadTree(result.data, simpleData));
			$(".openTree").each(function() {
				if ($(this).siblings('ul').length !== 0) {
					$(this).children('span').text("-");
				}
			});

			addTree();
			toggleTree();
			delTree();
			saveTree(btnID, callback, simpleData);
			resetNodeStyle();
		});
	}

	// 加载树
	function loadTree(result, simpleData) {
		var res = ''; //结果字符串
		if (simpleData) {
			result = parseJson(result).data;
		}
		if (result.length !== 0) {
			$.each(result, function(index, el) {
				var childRes = ''; //子集结果字符串
				if (el.child.length !== 0) {
					childRes = loadTree(el.child, false); //递归
				}
				res += '<li class="child" data-id="' + el.id + '" data-pid="' + el.pId + '">' +
					'<input type="text" value="' + el.name + '">' +
					'<div class="openTree"><span>+</span></div><div class="delTree"><span>x</span></div>' +
					childRes + '</li>';
			});
			res = '<ul><span class="tree-line-t"></span><span class="tree-line-c"></span><span class="tree-line-b"></span>' +
				res + '<li class="addTree"><span>+</span></li></ul>';
		}
		return res;
	}

	// 添加节点
	function addTree() {
		var childNode, dataId, dataPID;
		$(".addTree").off("click").on("click", function() {
			var $this = $(this),
				bortherLength = $this.siblings("li").length;

			if (bortherLength === 0 || $this.prev().children("input").val()) {
				dataId = bortherLength ? idStringify($this.prev().data("id")) : $this.parent().parent().data('id') + "-1";
				dataPID = bortherLength ? $this.prev().data("pid") : $this.parent().parent().data('id');
				childNode = '<li class="child" data-id="' +
					dataId + '" data-pId="' + dataPID +
					'"><input type="text" value=""><div class="openTree"><span>+</span></div><div class="delTree"><span>x</span></div></li>';
				$this.before(childNode);
			} else {
				return;
			}
			toggleTree(); //重新绑定切换按钮事件
			delTree(); //重新删除按钮事件
			resetNodeStyle();
		});
	}

	//展开关闭按钮切换
	function toggleTree() {
		$(".openTree").off("click").on("click", function() {
			var $this = $(this),
				$child = $this.children('span'),
				$next = $this.siblings('ul');
			var res = '<ul class="hidden"><span class="tree-line-t"></span><span class="tree-line-c"></span><span class="tree-line-b"></span><li class="addTree"><span>+</span></li></ul>';
			if(!$this.prev().val()){
				return;
			}
			if ($child.text() === "+") {
				$child.text("-");
				if ($next.length === 0) {
					$this.parent().append(res);
					addTree(); //重新绑定添加按钮事件
				}
			} else {
				$child.text("+");
			}
			$this.siblings('ul').toggleClass('hidden');
			resetNodeStyle();
		});
	}

	// 删除节点
	function delTree() {
		$(".delTree").off("click").on("click", function() {
			$(this).parent().remove();
			resetNodeStyle();
		});
	}

	// 保存树节点
	function saveTree(btnID, callback, simpleData) {
		var res;
		$(btnID).off("click").on("click", function() {
			var data = [],
				child = {};
			// 获取所有节点数据
			$('.child').each(function() {
				child = {
					"id": '' + $(this).data("id"),
					"pId": '' + $(this).data("pid"),
					"name": $(this).children("input").val()
				}
				data.push(child);
			});

			if (simpleData) {
				res = {
					"data": data
				};
			} else {
				res = parseJson(data);
			}
			callback(res);
		});
	}

	// 格式化json数据为嵌套数据类型
	function parseJson(data) {
		var result = {
			"data": []
		};
		for (var i = 0; i < data.length; i++) {
			for (var j = 0; j < data.length; j++) {
				if (!data[j].child) {
					data[j].child = [];
				}
				if (data[j].pId == data[i].id) {
					data[i].child.push(data[j]);
				}
			}
		}
		$.each(data, function(index, el) {
			if (el.pId == 0) {
				result.data.push(el);
			}
		});
		return result;
	}

	// 切换父节点居中显示
	function resetNodeStyle() {
		function treeNodeMiddle(node) {
			var childNode = node.parent().children("input"),
				pHeight = node.parent().height(),
				cHeight = childNode.height();

			node.parent().children("input,.openTree,.delTree").css({
				"position": "relative",
				"top": (pHeight - cHeight) / 2 + "px"
			});
		}

		$(".openTree").each(function() {
			treeNodeMiddle($(this));
		});
		resetLine();
	}

	// 修改连接线
	function resetLine() {
		$(".tree-line-t").each(function() {
			var $this = $(this),
				tHeight = $this.siblings("li").first().height();
			$this.css({
				"top": tHeight / 2 + 'px'
			})
		});

		$(".tree-line-c").each(function() {
			var $this = $(this),
				tHeight = $this.siblings("li").first().height(),
				cHeight = $(this).parent().height();
			$this.css({
				"top": tHeight / 2 + 3 + 'px',
				"height": cHeight - tHeight / 2 - 13 + 'px'
			})
		});

		$(".tree-line-b").each(function() {
			if ($(this).siblings(".child").length === 0) {
				$(this).addClass('hidden');
			} else {
				$(this).removeClass('hidden');
			}
		});
	}

	//处理data-id
	function idStringify(id) {
		var a, b;
		if (id.toString().indexOf("-") !== -1) {
			a = id.split("-");
			b = parseInt(a[a.length - 1]) + 1;
			a.pop();
			a.push(b);
			return a.join("-");
		} else {
			return parseInt(id) + 1;
		}
	}

	return {
		/**
		 * 初始化树
		 * 	{string} url        	[树的json数据请求路径]
		 * 	{string} domID      	[树的div容器ID]
		 * 	{string} btnID      	[保存按钮ID]
		 * 	{function} callback 	[处理结果的回调函数]
		 * 	{Boolean} simpleData	[是否使用简单数据类型][使用和返回的数据类型一致]
		 */

		/*   简单数据类型
			{
				"status": {
					"code": 200,
					"message": "获取数据成功"
				},
				"data": [{
					"id": "1",
					"pId": "0",
					"name": "个人信息"
				}, {
					"id": "1-2",
					"pId": "1",
					"name": "电话号码"
				}, {
					"id": "2",
					"pId": "0",
					"name": "企业信息"
				}, {
					"id": "2-1",
					"pId": "2",
					"name": "公司名字"
				}, {
					"id": "2-3",
					"pId": "2",
					"name": "公司地址"
				}]
			}
		 */

		/*   镶嵌数据类型
			{
				"status": {
					"code": 200,
					"message": "获取数据成功"
				},
				"data": [{
					"id": "1",
					"pId": "0",
					"name": "个人信息",
					"child": [{
						"id": "1-2",
						"pId": "1",
						"name": "电话号码",
						"child": []
					}]
				}, {
					"id": "2",
					"pId": "0",
					"name": "企业信息",
					"child": [{
						"id": "2-1",
						"pId": "2",
						"name": "公司名字",
						"child": []
					}, {
						"id": "2-3",
						"pId": "2",
						"name": "公司地址",
						"child": []
					}]
				}]
			}
		 */
		"initTree": function(url, domID, btnID, callback, simpleData) {
			initTree(url, domID, btnID, callback, simpleData);
		}
	}
}